package util

import (
	"fmt"
	"io"
	"os"
	"os/exec"
	"strings"
)

// ContactTsFilesByFfmpeg 使用FFmpeg合并视频
func ContactTsFilesByFfmpeg(dir string, fileNames []string, outputFileName string) error {
	builder := strings.Builder{}
	for _, item := range fileNames {
		builder.WriteString(fmt.Sprintf("%s/%s", dir, item))
		builder.WriteRune('|')
	}
	text := builder.String()
	command := []string{"-i", fmt.Sprintf("concat:%s", text[:len(text)-1]), "-c", "copy", "-bsf:a", "aac_adtstoasc", "-movflags", "+faststart", fmt.Sprintf("./%s", outputFileName)}
	cmd := exec.Command("ffmpeg", command...)
	cmd.Stdout = os.Stdout
	cmd.Stderr = os.Stderr
	return cmd.Run()
}

// ContactTsFilesDirectly 直接合并所有文件的字节
func ContactTsFilesDirectly(dir string, fileNames []string, outputFileName string) error {
	outFile, err := os.OpenFile("./"+outputFileName, os.O_CREATE|os.O_APPEND, 0644)
	if err != nil {
		return err
	}
	for _, item := range fileNames {
		currentFileName := fmt.Sprintf("%s/%s", dir, item)
		currentFile, err := os.Open(currentFileName)
		if err != nil {
			return err
		}
		buf := make([]byte, 1024*10)
		io.CopyBuffer(outFile, currentFile, buf)
		currentFile.Close()
	}
	outFile.Close()
	return nil
}
